<template>
  <el-container class="cc">
    <el-main class="content-section">
      <div class="top-header">
        <h2>患者管理</h2>
        <div class="toolbar">
          <el-button type="primary" @click="addPatient">添加患者</el-button>
          <!-- <el-button type="primary" @click="dialogVisible = true">添加医生</el-button> -->
        </div>
      </div>

      <div class="search-export-header">
        <div class="search-bar">
          <el-input v-model="search.name" placeholder="搜索姓名" class="search-item"></el-input>
          <el-input v-model="search.hospital" placeholder="搜索医院" class="search-item"></el-input>
          <el-select v-model="search.status" placeholder="账号状态" class="search-item">
            <el-option label="已启用" value="已启用"></el-option>
            <el-option label="已停用" value="已停用"></el-option>
            <el-option label="未启用" value="未启用"></el-option>
          </el-select>
          <el-date-picker
            v-model="search.createDateRange"
            type="daterange"
            range-separator="至"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
            format="YYYY-MM-DD"
            class="search-item"
          ></el-date-picker>
          <el-button type="primary" @click="searchDoctors">搜索</el-button>
        </div>
        <div class="export-btn">
          <el-button type="success" @click="exportDoctors">导出</el-button>
        </div>
      </div>
      <el-scrollbar style="height: calc(100vh - 200px);">
        <el-table :data="patient1" style="width: 100%">
          <el-table-column prop="name" label="患者姓名" width="150"></el-table-column>
          <el-table-column prop="sex" label="患者性别" width="90"></el-table-column>
          <el-table-column prop="addr" label="现居住地" width="200"></el-table-column>
          <el-table-column prop="date" label="上次就诊时间"></el-table-column>
          <el-table-column prop="count" label="就诊次数"></el-table-column>
          <el-table-column prop="doctor" label="医生"></el-table-column>
          <el-table-column prop="hospital" label="附属医院"></el-table-column>
          <el-table-column label="操作" width="200">
            <template v-slot="scope">
              <div class="action-buttons">
                <el-button type="text" size="small" @click="editPatient(scope.row)">编辑</el-button>
                <el-button type="text" size="small" @click="deletePatient(scope.row)">删除</el-button>
              </div>
            </template>
          </el-table-column>
        </el-table>
        <div class="pagination-container">
          <el-select v-model="pageSize" @change="handlePageSizeChange" placeholder="每页显示条数">
            <el-option label="10条/页" :value="10"></el-option>
            <el-option label="20条/页" :value="20"></el-option>
            <el-option label="30条/页" :value="30"></el-option>
            <el-option label="40条/页" :value="40"></el-option>
          </el-select>
          <el-pagination
            @current-change="handleCurrentChange"
            :current-page="currentPage"
            :page-size="pageSize"
            layout="total, prev, pager, next, jumper"
            :total="total"
          ></el-pagination>
        </div>
      </el-scrollbar>
    </el-main>
  </el-container>
  <el-dialog
    v-model="dialogVisible"
    :title="dialogTitle"
    width="500px"
    @closed="resetForm" 
  >
    <el-form :model="currentpatient"  ref="doctorForm" label-width="80px">
      <el-form-item label="姓名">
        <el-input v-model="currentpatient.name"></el-input>
      </el-form-item>
      <el-form-item label="性别">
        <el-input v-model="currentpatient.sex"></el-input>
      </el-form-item>
      <el-form-item label="现居住地">
        <el-input v-model="currentpatient.addr"></el-input>
      </el-form-item>
      <el-form-item label="上次就诊时间">
        <el-input v-model="currentpatient.date"></el-input>
      </el-form-item>
      <el-form-item label="就诊次数">
        <el-input v-model="currentpatient.count"></el-input>
      </el-form-item>
      <el-form-item label="医生">
        <el-input v-model="currentpatient.doctor"></el-input>
      </el-form-item>
      <el-form-item label="附属医院">
        <el-input v-model="currentpatient.hospital"></el-input>
      </el-form-item>
    </el-form>
    <template #footer>
      <div class="dialog-footer">
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="submit(currentpatient)">确认</el-button>
      </div>
    </template>
  </el-dialog>
</template>

<script setup lang="ts">
import { useRouter } from 'vue-router';
import { ref, computed, onBeforeMount } from 'vue';
import axios from 'axios';
import { ElMessage } from 'element-plus';
import { addPatientApi, getPatientAllApi, getPatientPageApi, updatePatientApi } from '@/api/api';

const selectedMenuItem = ref('patient');
const router = useRouter();
const dialogVisible = ref(false)
const dialogTitle = ref('患者信息');
const patient1=ref([])
interface patient {
  id: number;
  name: string;
  sex: string;
  hospital: string;
  doctor: string;
  addr:string;
  date: string;
  count: string;
}
const currentpatient = ref<patient>({
  id:0,
  name: '',
  sex: '',
  hospital: '',
  doctor: '',
  addr:'',
  date: '',
  count: '',
});
const resetForm = () => {
  currentpatient.value = {
    id : 0,
  name: '',
  sex: '',
  hospital: '',
  doctor: '',
  addr:'',
  date: '',
  count: '',
  };
};

const search = ref({
  name: '',
  hospital: '',
  status: '',
  createDateRange: []
});
const currentPage = ref(1);
const pageSize = ref(12);
const total = ref(0);

onBeforeMount(() => {
      lista();
    });
async function lista() {

      const response = await getPatientPageApi();
      
      // 测试
      console.log(response.data); // 访问 data
      console.log(response.code); // 访问 code
  
      // 当后端返回200表示成功
      if (response.code === 200) {
        console.log(response.data.records)
        patient1.value = response.data.records; // 数据在response.data
      } 

  };
  const handpage = () => {
      //改变分页
        //再次获取数据  在vu3 中取消了this这个东西， 这里直接像我们原先写传统js 中的方法直接 `方法名()`直接调用
        lista();
    }


const logout = () => {
  // 处理登出逻辑
};

const searchDoctors = () => {
  // 触发重新计算filteredDoctors
};

const exportDoctors = () => {
  // 处理导出逻辑，将页面的数据导出为excel
};
const isEditMode = ref(false);
const addPatient = ()=>{
  dialogTitle.value = '添加患者';
  dialogVisible.value=true;
  currentpatient;
  isEditMode.value = true;
}

const handleCurrentChange = (page) => {
  currentPage.value = page;
};

const handlePageSizeChange = (size) => {
  pageSize.value = size;
};


const editPatient = (patient) => {
  dialogVisible.value=true
  dialogTitle.value = '修改患者信息';
  currentpatient.value = { ...patient };
  isEditMode.value=false
  // 编辑医生信息的逻辑
};
async function submit(currentpatient) {
  console.log(currentpatient)
  if(isEditMode.value){
    try {
    const response = await addPatientApi(currentpatient);
    
    // 测试
    console.log(response.data); // 访问 data
    console.log(response.code); // 访问 code

    // 当后端返回200表示成功
    if (response.code === 200) {
      ElMessage({
        message: '添加成功',
        type: 'success',
        plain: true,
      });
      // router.push({ name: 'doctor' });
      dialogVisible.value = false
      const currentRoute = router.currentRoute.value;
          router.replace({ path: '/index', query: { t: Date.now() } }).then(() => {
            router.replace(currentRoute.fullPath);
          });
    } else {
      ElMessage({
        message: response.msg,
        type: 'error',
        plain: true,
        duration: 1500,
      });
    }
  } catch (error) {
    // 当出现前端异常时, 也应该给出合理提示
    ElMessage({
      message: '添加失败',
      type: 'error',
      plain: true,
      duration: 1500,
    });
  }
  }else{
    try {
    const response = await updatePatientApi(currentpatient);
    
    // 测试
    console.log(response.data); // 访问 data
    console.log(response.code); // 访问 code

    // 当后端返回200表示成功
    if (response.code === 200) {
      ElMessage({
        message: '修改成功',
        type: 'success',
        plain: true,
      });
      dialogVisible.value = false
      const currentRoute = router.currentRoute.value;
          router.replace({ path: '/index', query: { t: Date.now() } }).then(() => {
            router.replace(currentRoute.fullPath);
          });
    } else {
      ElMessage({
        message: response.msg,
        type: 'error',
        plain: true,
        duration: 1500,
      });
    }
  } catch (error) {
    // 当出现前端异常时, 也应该给出合理提示
    ElMessage({
      message: '修改失败',
      type: 'error',
      plain: true,
      duration: 1500,
    });
  }
  }
  
};
async function deletePatient(row) {
  try {
    console.log(row.id)
    const response = await axios.get(`http://localhost:8080/patient/${row.id}`);;
    
    // 测试
    console.log(response.data); // 访问 data
    console.log(response.data.code); // 访问 code

    // 当后端返回200表示成功
    if (response.data.code == 200) {
      ElMessage({
        message: '删除成功',
        type: 'success',
        plain: true,
      });
      const currentRoute = router.currentRoute.value;
          router.replace({ path: '/index', query: { t: Date.now() } }).then(() => {
            router.replace(currentRoute.fullPath);
          });
    } else {
      ElMessage({
        message: '删除失败',
        type: 'error',
        plain: true,
        duration: 1500,
      });
    }
  } catch (error) {
    // 当出现前端异常时, 也应该给出合理提示
    ElMessage({
      message: '删除失败',
      type: 'error',
      plain: true,
      duration: 1500,
    });
  }

} 


</script>

<style scoped>
.top-header,
.search-export-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 0 20px;
  background-color: #f2f2f2;
  border-bottom: 1px solid #e2e2e2;
}

.toolbar {
  display: flex;
  align-items: center;
}

.toolbar span {
  margin-right: 20px;
}

.content-section {
  padding: 20px;
}

.search-bar {
  display: flex;
  align-items: center;
}

.search-bar .search-item {
  margin-right: 10px;
  width: 200px;
}

.export-btn {
  margin-left: auto;
}

.pagination-container {
  display: flex;
  justify-content: center;
  align-items: center;
  margin-top: 20px;
}

.pagination-container .el-select {
  width: 120px;
  margin-right: 20px;
}

.action-buttons {
  display: flex;
  justify-content: space-between;
  width: 150px;
}
</style>
